package com.qf.web.filter;

import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.Base64Util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AutoLoginFilter",value = "/index.jsp")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    //判断是否已登录
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        User user=(User)request.getSession().getAttribute("user");
        if (user != null) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //如果没有登录
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("userinfo")){
                    String userinfo = cookie.getValue();
                    userinfo= Base64Util.decode(userinfo);
                    String[] arr = userinfo.split("#");
                    if(arr.length==2){
                        String username=arr[0];
                        String password=arr[1];
                        System.out.println(username+"/t"+password);
                        UserService userService = new UserServiceImpl();
                        try {
                            User u = userService.login(username,password);
                            request.getSession().setAttribute("user",u);
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                            //删除cookie
                            Cookie deletecookie = new Cookie("userinfo","");
                            deletecookie.setPath(request.getContextPath());
                            deletecookie.setMaxAge(0);
                            response.addCookie(deletecookie);
                        }
                    }
                }
            }
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
